<?php

namespace app\common\library;

use fast\Http;

class Location {






    /**
     *
     * 地址转换坐标
     * @return array
     *
     */
    public static function addressToLocation($address): array
    {

        $apikey = 'KQEBZ-HG56J-NXOFG-F73GJ-CXDP5-H2FLK';
        // 使用腾讯地图api解析地址
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?address={$address}&key=${$apikey}";

        // 发送请求
        $response = Http::get($url);

        // 解析响应
        $response = json_decode($response, true);

        return $response['result']['location'];

    }


    /**
     * 计算两个坐标之间的距离单位为公里
     * @param $lat1
     * @param $lon1
     * @param $lat2
     * @param $lon2
     * @return float|int
     */
    public static function calculateDistance($lat1, $lon1, $lat2, $lon2)
    {
        $earthRadius = 6371; // 地球半径，单位为公里

        $dLat = deg2rad($lat2 - $lat1);
        $dLon = deg2rad($lon2 - $lon1);

        $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2) * sin($dLon/2);
        $c = 2 * atan2(sqrt($a), sqrt(1-$a));

        $distance = $earthRadius * $c;

        return round($distance, 2); // 保留两位小数
    }
}